//
//  ViewController.m
//  WaveAnimationDemo
//
//  Created by jintao he on 2018/12/17.
//  Copyright © 2018 jintao he. All rights reserved.
//

#import "ViewController.h"
#import <CoreText/CoreText.h>
#import "HJTWaterView.h"

@interface ViewController ()<HJTWaterPathDelegate>

@property (nonatomic, strong) HJTWaterView *waterWaveView;

@property (nonatomic, strong) UIFont *font;
@property (nonatomic, strong) UIView *labelView;
@property (nonatomic, strong) CAShapeLayer * maskLayer;
@property (nonatomic) CTFontRef fontRef;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configVC];
}

#pragma mark -- configurations

-(void)configVC{
    self.fontRef = CTFontCreateWithName((__bridge CFStringRef)_font.fontName, _font.pointSize, NULL);
    [self configWaterWave];
    [self configText];
}

- (void)configWaterWave {
    [self.view addSubview:self.waterWaveView];
}

- (void)configText {
    _font = [UIFont systemFontOfSize:50.];
    _labelView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, 70, 70)];
    [self.waterWaveView addSubview:_labelView];
}

#pragma mark - Update Text Layer
- (void)updateMaskLayer:(CGMutablePathRef)p {
    
    CATextLayer * text1 = [self createTextLayer:@"RD"];
    CATextLayer * text2 = [self createTextLayer:@"RD"];
    
    [text1 setForegroundColor:self.waterWaveView.waterColor.CGColor];
    [text1 addSublayer:text2];
    
    text1.alignmentMode = kCAAlignmentCenter;
    text2.alignmentMode = kCAAlignmentCenter;
    
    self.maskLayer = [[CAShapeLayer alloc] init];
    self.maskLayer.path = p;
    text2.mask = self.maskLayer;
    
    self.labelView.layer.sublayers = nil;
    [self.labelView.layer addSublayer:text1];
}

- (CATextLayer*)createTextLayer:(NSString*)content {
    CATextLayer *text = [CATextLayer layer];
    CGRect bound = _labelView.bounds;
    bound.origin.y = bound.origin.y;
    [text setFrame:bound];
    [text setString:(id)content];
    [text setFont:self.fontRef];
    [text setFontSize:_font.pointSize];
    
    [text setForegroundColor:[UIColor whiteColor].CGColor];
    [text setContentsScale:[[UIScreen mainScreen] scale]];
    [text setBackgroundColor:[UIColor clearColor].CGColor];
    
    return text;
}

#pragma mark -- HJTWaterPathDelegate

-(void)wavePath:(CGMutablePathRef)path{
    [self updateMaskLayer:path];
}

#pragma mark -- lazy

-(HJTWaterView *)waterWaveView{
    if (!_waterWaveView) {
        _waterWaveView = [[HJTWaterView alloc] initWithFrame:CGRectMake(0, 0, 100,   100)];
        _waterWaveView.layer.cornerRadius = 50;
        _waterWaveView.layer.masksToBounds = YES;
        _waterWaveView.center = CGPointMake(self.view.bounds.size.width/2.0, self.view.bounds.size.height/2.0);
        
        _waterWaveView.waterColor = [UIColor colorWithRed:100/255.0f green:167/255.0f blue:229/255.0f alpha:1];
        _waterWaveView.waterLevelY = 40.f;
        
        _waterWaveView.waveDelegate = self;
    }
    return _waterWaveView;
}


@end
